#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <getopt.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "getip.h"

/*
 * file name : getip.c
 * abstract  : get IP, MAC, etc...
 * author    : xiaozhi
 */

// #define EMBEDDED

static char mac_address[20];
static char ip_address[20];
static char bcast[20];
static char mask[20];
static char gateway[20];
char *ifconfig_txt = "/tmp/ifconfig.txt";
char *route_txt = "/tmp/route.txt";

static void ifconfig()
{
	FILE *stream;
	FILE *if_file;
	char ip_buf[1024];
	
	stream = popen("ifconfig","r");
	if_file = fopen(ifconfig_txt, "w+");
	fread(ip_buf, sizeof(char), sizeof(ip_buf), stream);
	fwrite(ip_buf, 1, sizeof(ip_buf), if_file);

	pclose(stream);
	fclose(if_file);
}

static void find_value(char *file)
{
	FILE *fp;
	char buf[512];
	int i = 0;

	memset(buf, '\0', sizeof(buf));
	if ((fp = fopen(file, "r")) == NULL) {
		printf("File : %s failed to open\n", file);
	}

	while (!feof(fp)) {
		fscanf(fp, "%s", buf);
		switch(i) {
			case MAC_POS:
				sprintf(mac_address, "%s", buf);
				printf("MAC address : %s\n", mac_address);
				break;
			case ADDR_POS:
				sprintf(ip_address, "%s", buf+5);
				printf("IP address  : %s\n", ip_address);
				break;
			case BCAST:
				sprintf(bcast, "%s", buf+6);
				printf("Bcast       : %s\n", bcast);
				break;
			case MASK:				
				sprintf(mask, "%s", buf+5);
				printf("Mask        : %s\n", mask);
				break;
		}
		i++;
	}
	fclose(fp);
}

static void route()
{
	FILE *route;
	FILE *gw_file;
	FILE *fp;
	char gw_buf[1024];

	#ifdef EMBEDDED
	route  = popen("route","r");
	#else	/* pc */
	route  = popen("ip route show","r");
	#endif
	gw_file = fopen(route_txt, "w+");
	fread(gw_buf, sizeof(char), sizeof(gw_buf), route);
	fwrite(gw_buf, 1, sizeof(gw_buf), gw_file);

	pclose(route);
	fclose(gw_file);
}

/*
 * return value : 
 *			  0 : 没有设定网关
 */
static int gate_way(char *file)
{
	FILE *fp;
	char buf[1024];
	int flag = 0;

	memset(buf, '\0', sizeof(buf));
	if ((fp = fopen(file, "r")) == NULL) {
		printf("File : %s failed to open\n", file);
	}

	while (!feof(fp)) {
		fscanf(fp, "%s", buf);
		#ifdef EMBEDDED
		if (strcmp("default", buf) == 0) {
			fscanf(fp, "%s", buf);
			sprintf(gateway, "%s", buf);
			printf("Gateway     : %s\n", gateway);
			flag = 1;
		}
		#else
		if (strcmp("via", buf) == 0) {
			fscanf(fp, "%s", buf);
			sprintf(gateway, "%s", buf);
			printf("Gateway     : %s\n", gateway);
			flag = 1;
		}
		#endif
	}
	fclose(fp);

	return flag;
}

int main()
{
	ifconfig();
	find_value(ifconfig_txt);

	route();
	gate_way(route_txt);

	return 0;
}







